<template>
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24" v-if="this.currentCostType == 1">
          <a-col :span="4">
            <a-form-item label="材料类型种类">
              <a-select placeholder="请选择材料类型种类" v-model="materialTypeKind" style="width: 100%" @change="changeMaterialTypeKind">
                <a-select-option value="1">主要项目</a-select-option>
                <a-select-option value="2">辅要项目</a-select-option>
                <a-select-option value="3">赠品项目</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-model-item label="材料类型" prop="productType">
              <a-tree-select
                v-model="queryParam1.materialType"
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="treeData"
                :replaceFields="dataFields"
                placeholder="请先选择材料类型种类"
                @change="changeMaterialType"
              >
              </a-tree-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="供应商">
              <a-select
                show-search
                :allowClear="true"
                placeholder="请选择供应商"
                option-filter-prop="children"
                v-model="queryParam1.supplierId"
                style="width: 100%"
                :filter-option="filterOptionSupplier"
                @change="changeSupplier">
                <a-select-option :value="item.id" v-for="(item,index) in supplierData" :key="index">
                  {{item.supplierName}}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="5">
            <a-form-item label="搜索条件">
              <a-input-group compact>
                <a-select default-value="1" style="width: 30%" @change="changeConditionType">
                  <a-select-option value="1">
                    名称
                  </a-select-option>
                  <a-select-option value="2">
                    型号
                  </a-select-option>
                  <a-select-option value="3">
                    规格
                  </a-select-option>
                  <a-select-option value="4">
                    品牌
                  </a-select-option>
                </a-select>
                <a-input placeholder="请输入搜索内容" style="width: 70%" v-model="conditionValue"></a-input>
              </a-input-group>
            </a-form-item>
          </a-col>
          <a-col :span="4">
                    <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                      <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                      <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
                    </span>
          </a-col>
        </a-row>

        <a-row :gutter="24" v-if="this.currentCostType == 2">
          <a-col :span="5">
            <a-form-item label="请选择工种">
              <a-select v-model="queryParam2.kindOfWorkType" placeholder="请选择工种" @change="changeKindOfWork" :allowClear="true">
                <a-select-option :value="item.id" v-for="(item,index) in kindOfWorkData" :key="index">{{item.kindOfWork}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div>
      <a-tabs default-active-key="1" @change="callback" style="height: 100%">
        <a-tab-pane tab="材料成本" key="1" forceRender >
          <a-table
            ref="table"
            size="middle"
            :scroll="{y:500}"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource1"
            :pagination="ipagination1"
            :loading="loading"
            :customRow="setRow1"
            :rowSelection="{
              selectedRowKeys: selectedRowKeys1,
              onSelectAll:onSelectAll1,
              onSelect:onSelect1,
              onChange: onSelectChange1,
              type:'checkbox'
            }"
            class="j-table-force-nowrap"
            @change="handleTableChange1">
          </a-table>
        </a-tab-pane>
        <a-tab-pane tab="人工成本" key="2" forceRender>
          <a-table
            ref="table"
            size="middle"
            :scroll="{y:500}"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource2"
            :pagination="ipagination2"
            :loading="loading"
            :customRow="setRow2"
            :rowSelection="{
              selectedRowKeys: selectedRowKeys2,
              onSelectAll:onSelectAll2,
              onSelect:onSelect2,
              onChange: onSelectChange2,
              type:'checkbox'
            }"
            class="j-table-force-nowrap"
            @change="handleTableChange2">
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </div>
  </a-modal>
</template>

<script>
  import { filterObj } from '@/utils/util'
  import { getAction, postAction } from '@/api/manage'
  export default {
    name: "addCostProductionModal",
    data() {
      return {
        currentCustomerId: 0,         //当前用户id
        currentCostType: 1,           //当前选择的成本类型
        costProductions: [],
        currentSubcategoryValue: 0,   //当前选择的子分类
        basicInstallationValue: false, //是否显示子分类查询下拉框
        width: '95%',
        treeData:[],
        dataFields: {
          title: 'materialTypeName',
          key: 'id',
          value: 'id',
          children: "children"
        },
        defaultConditionType: 1,
        conditionValue: '',
        materialTypeKind: "",
        model: {},
        title: "",
        names: [],
        columns:[],
        visible: false,
        placement: 'right',
        description: '',
        // 查询条件
        queryParam1: {},
        queryParam2: {},
        //职务条件
        post: '',
        // 表头
        columns1: [
          /*{
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 50,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },*/
          {
            title:'材料编号',
            align:"center",
            dataIndex: 'materialSerial'
          },
          {
            title:'名称',
            align:"center",
            dataIndex: 'materialName',
            width: "10%",
            customCell:() => {
              return {
                style: {
                  wordWrap:'break-word',
                  wordBreak:'break-all',
                  whiteSpace:'normal',
                  minHeight:'50px',
                  width: '10%',
                }
              }
            }
          },
          {
            title:'型号',
            align:"center",
            dataIndex: 'modelNumber',
            width: "10%",
            customCell:() => {
              return {
                style: {
                  wordWrap:'break-word',
                  wordBreak:'break-all',
                  whiteSpace:'normal',
                  minHeight:'50px',
                  width: '10%',
                }
              }
            }
          },
          {
            title:'规格',
            align:"center",
            dataIndex: 'specifications',
            width: "10%",
            customCell:() => {
              return {
                style: {
                  wordWrap:'break-word',
                  wordBreak:'break-all',
                  whiteSpace:'normal',
                  minHeight:'50px',
                  width: '10%',
                }
              }
            }
          },
          {
            title:'品牌',
            align:"center",
            dataIndex: 'brand',
            width: "10%",
            customCell:() => {
              return {
                style: {
                  wordWrap:'break-word',
                  wordBreak:'break-all',
                  whiteSpace:'normal',
                  minHeight:'50px',
                  width: '10%',
                }
              }
            }
          },
          {
            title:'单位',
            align:"center",
            dataIndex: 'unit',
            width: "5%",
            customCell:() => {
              return {
                style: {
                  wordWrap:'break-word',
                  wordBreak:'break-all',
                  whiteSpace:'normal',
                  minHeight:'50px',
                  width: '5%',
                }
              }
            }
          },
          {
            title:'材料类型',
            align:"center",
            dataIndex: 'materialTypeName'
          },
          {
            title:'供应商',
            align:"center",
            dataIndex: 'ghSupplychainSupplier.supplierName',
            width: "10%",
            customCell:() => {
              return {
                style: {
                  wordWrap:'break-word',
                  wordBreak:'break-all',
                  whiteSpace:'normal',
                  minHeight:'50px',
                  width: '10%',
                }
              }
            }
          },
          {
            title:'材料状态',
            align:"center",
            dataIndex: 'status',
            customRender:function (text) {
              return text == 1 ? <a-tag color="green">启用</a-tag> : <a-tag color="orange">禁用</a-tag>
            }
          },
          {
            title:'市场价/元',
            align:"center",
            dataIndex: 'marketPrice',
            customRender:function (text) {
              if (text == "" || text == null){
                return "-"
              }else {
                return text
              }
            }
          },
          {
            title:'预算价/元',
            align:"center",
            dataIndex: 'estimatedCost',
            customRender:function (text) {
              if (text == "" || text == null){
                return "-"
              } else {
                return text
              }
            }
          },
          {
            title:'成本价/元',
            align:"center",
            dataIndex: 'costPrice',
            customRender:function (text) {
              if (text == "" || text == null){
                return "-"
              } else {
                return text
              }
            }
          },
        ],
        columns2: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: "5%",
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '工种类型名称',
            align: "center",
            dataIndex: 'kindOfWorkTypeName',
            width: "15%"
          },
          {
            title: '施工部位',
            align: "center",
            dataIndex: 'constructionPlace',
            width: "15%"
          },
          {
            title: '工价',
            align: "center",
            dataIndex: 'labourCost',
            width: "10%"
          },
          {
            title: '单位',
            align: "center",
            dataIndex: 'unit',
            width: "10%"
          },
          {
            title:'规格',
            align:"center",
            dataIndex: 'specifications',
            width: "15%"
          },
          {
            title:'备注',
            align:"center",
            dataIndex: 'remark',
            width: '25%',
            customCell:() => {
              return {
                style: {
                  wordWrap:'break-word',
                  wordBreak:'break-all',
                  whiteSpace:'normal',
                  minHeight:'50px',
                  width: '25%',
                }
              }
            }
          },
        ],
        //数据集
        dataSource1: [],
        dataSource2: [],
        loading: false,
        selectedRowKeys1: [],
        selectedRows1: [],
        selectedRowKeys2: [],
        selectedRows2: [],
        ipagination1:{
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        ipagination2:{
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        /* 排序参数 */
        isorter:{
          column: 'createTime',
          order: 'desc',
        },
        materialTypeData:[],
        kindOfWorkData:[],
        supplierData:[],
        url: {
          materialList: "/ghSupplychainMaterial/costMaterialList",
          priceList: "/ghPriceManagement/list",
          add: "/ghCustomerChooseCost/add",
          materialTypeList: "/ghSupplychainMaterialType/list",
          kindOfWorkList: "/ghKindOfWork/queryList",
          supplierList: "/ghSupplychainSupplier/allList",
        },
        conditionType: 1
      }
    },
    created() {
      this.initKindOfWorkList();
      this.initMaterialTypeList();
      this.loadSupplierData();
    },
    mounted() {
      this.columns = this.columns1;
    },
    methods: {
      changeConditionType(value){
        this.conditionType = value;
        /*this.queryParam1.conditionType = value;*/
      },
      initTreeData(materialTypeKind) {
        getAction(this.url.materialTypeList,{materialType:materialTypeKind}).then(res => {
          if (res.success) {
            this.treeData = res.result;
          }
        });
      },
      initKindOfWorkList(){
        getAction(this.url.kindOfWorkList).then((res) => {
          if (res.success) {
            this.kindOfWorkData = res.result || res.result.records;
          }
        })
      },
      initMaterialTypeList(){
        getAction(this.url.materialTypeList).then((res) => {
          if (res.success) {
            this.materialTypeData = res.result || res.result.records;
          }
        })
      },
      callback(key) {
        this.currentCostType = key;
        if (key == 1){
          this.columns = this.columns1;
        }else {
          this.columns = this.columns2;
        }
        this.loadData(key,1)
      },
      changeMaterialType(value){
        this.loadData(1,1);
      },
      searchQuery() {
        this.queryParam1.conditionValue = this.conditionValue;
        this.loadData(1,1);
      },
      //工种类型改变时
      changeKindOfWork(value){
        if (value == "" || value == null){
          this.ipagination2.current = 1
          this.ipagination2.pageSize = 10
        }
        this.loadData(2,1)
      },
      searchReset() {
        this.queryParam1 = {};
        this.queryParam2 = {};
        this.materialTypeKind = "";
        this.conditionValue = ""
        this.treeData = [];
        this.ipagination1.current = 1
        this.ipagination1.pageSize = 10
        this.loadData(1,1);
      },
      handleCancel() {
        this.visible = false;
        this.queryParam1 = {};
        this.queryParam2 = {};
        this.onClearSelected();
        this.conditionType = 1;
        this.conditionValue = ''
      },
      handleOk() {
        const that = this;
        // 触发表单验证
        that.confirmLoading = true;
        let params = {};
        if (this.selectedRows1.length >= 1) {
          for (let i = 0; i < this.selectedRows1.length; i++) {
            this.costProductions.push({
              chooseCostType: 1,
              chooseMaterialType: this.selectedRows1[i].materialType,
              customerId: this.currentCustomerId,
              materialId: this.selectedRows1[i].id,
              quantity: 1,
              unitPrice: this.selectedRows1[i].costPrice,
              costTypeSubtotal: this.selectedRows1[i].costPrice,
            })
          }
        }
        if (this.selectedRows2.length >= 1){
          for (let i = 0; i < this.selectedRows2.length; i++) {
            this.costProductions.push({
              chooseCostType: 2,
              chooseKindOfWork: this.selectedRows2[i].kindOfWorkType,
              customerId: this.currentCustomerId,
              priceId: this.selectedRows2[i].id,
              quantity: 1,
              unitPrice: this.selectedRows2[i].labourCost,
              costTypeSubtotal: this.selectedRows2[i].labourCost,
            })
          }
        }
        if (this.costProductions.length !== 0){
          params.costProductions = this.costProductions;
        }else {
          this.$message.error("请至少选择一条有效数据");
          return;
        }
        params.customerId = that.currentCustomerId;
        postAction(that.url.add, params).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            that.$emit('ok');
          } else {
            that.$message.warning(res.message);
          }
        }).finally(() => {
          that.confirmLoading = false;
          this.visible = false;
          this.costProductions = [];
          this.defaultConditionType = 1;
        })
      },
      add() {
        this.visible = true;
      },
      loadData(costType,arg) {
        let params = {};//查询条件
        let url = "";
        this.loading = true;
        if (costType === 1){
          if (arg === 1) {
            this.ipagination1.current = 1;
          }
          url = this.url.materialList;
          params = this.getQueryParams1();
          params.conditionType = this.conditionType;
          getAction(url, params).then((res) => {
            if (res.success) {
              this.dataSource1 = res.result.records;
              this.ipagination1.total = res.result.total;
            }
          }).finally(() => {
            this.loading = false
          })
        }else {
          if (arg === 1) {
            this.ipagination2.current = 1;
          }
          url = this.url.priceList;
          params = this.getQueryParams2();
          getAction(url, params).then((res) => {
            if (res.success) {
              this.dataSource2 = res.result.records;
              this.ipagination2.total = res.result.total;
            }
          }).finally(() => {
            this.loading = false
          })
        }
      },
      onSelectAll(selected, selectedRows, changeRows) {
        console.log("**************" + selected, selectedRows, changeRows);
      },
      onSelect(record, selected, selectedRows) {
      },
      onClearSelected() {
        this.selectedRowKeys1 = [];
        this.selectedRows1 = [];
        this.selectedRowKeys2 = [];
        this.selectedRows2 = [];
      },

      onSelectAll1(selected, selectedRows, changeRows) {
        if(selected) {
          let rows = [...selectedRows]
          this.selectedRows1 = this.selectedRows1.concat(rows)
        } else {
          changeRows.forEach(item => {
            const delIndex = this.selectedRows1.findIndex((val) => {
              return val.id === item.id
            })
            this.selectedRows1.splice(delIndex, 1)
          })
        }
      },
      onSelect1(record, selected) {
        if(selected) {
          this.selectedRows1.push(record);
        } else {
          const delIndex = this.selectedRows1.findIndex((val) => {
            return val.id === record.id
          })
          this.selectedRows1.splice(delIndex,1)
        }
      },
      onSelectChange1(selectedRowKeys) {
        this.selectedRowKeys1 = selectedRowKeys;
      },

      onSelectAll2(selected, selectedRows, changeRows) {
        if(selected) {
          let rows = [...selectedRows]
          this.selectedRows2 = this.selectedRows2.concat(rows)
        } else {
          changeRows.forEach(item => {
            const delIndex = this.selectedRows2.findIndex((val) => {
              return val.id === item.id
            })
            this.selectedRows2.splice(delIndex, 1)
          })
        }
      },
      onSelect2(record, selected) {
        if(selected) {
          this.selectedRows2.push(record);
        } else {
          const delIndex = this.selectedRows2.findIndex((val) => {
            return val.id === record.id
          })
          this.selectedRows2.splice(delIndex,1)
        }
      },
      onSelectChange2(selectedRowKeys) {
        this.selectedRowKeys2 = selectedRowKeys;
      },
      handleTableChange1(pagination, filters, sorter) {
        //分页、排序、筛选变化时触发
        //TODO 筛选
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field;
          this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
        }
        this.ipagination1 = pagination;
        this.loadData(1);
      },
      handleTableChange2(pagination, filters, sorter) {
        //分页、排序、筛选变化时触发
        //TODO 筛选
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field;
          this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
        }
        this.ipagination2 = pagination;
        this.loadData(2);
      },
      getQueryParams1() {
        var param = Object.assign({}, this.queryParam1, this.isorter);
        param.field = this.getQueryField1();
        param.pageNo = this.ipagination1.current;
        param.pageSize = this.ipagination1.pageSize;
        param.post = this.post;
        return filterObj(param);
      },
      getQueryField1() {
        //TODO 字段权限控制
      },
      getQueryParams2() {
        //获取查询条件
        let sqp = {}
        if(this.superQueryParams){
          sqp['superQueryParams']=encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        var param = Object.assign(sqp, this.queryParam2, this.isorter ,this.filters);
        param.field = this.getQueryField2();
        param.pageNo = this.ipagination2.current;
        param.pageSize = this.ipagination2.pageSize;
        return filterObj(param);
      },
      getQueryField2() {
        //TODO 字段权限控制
        var str = "id,";
        this.columns.forEach(function (value) {
          str += "," + value.dataIndex;
        });
        return str;
      },
      changeMaterialTypeKind(value){
        this.materialTypeKind = value;
        this.treeData = [];
        this.queryParam1 = {};
        this.initTreeData(value);
        this.loadData(1,1)
      },
      //表格行点击事件
      setRow1 (record) {
        return {
          on: {
            click: () => {
              let flag = false
              let keys = [];
              keys = this.selectedRowKeys1;
              if(keys.indexOf(record.id) >= 0) {
                flag=true
              }
              if(flag){
                keys.splice(keys.findIndex(item => item === record.id), 1)
                this.selectedRows1.splice(this.selectedRows1.findIndex(item => item === record.id),1)
              } else {
                keys.push(record.id)
                this.selectedRows1.push(record);
              }
            }
          }
        }
      },
      //表格行点击事件
      setRow2 (record) {
        return {
          on: {
            click: () => {
              let flag = false
              let keys = [];
              keys = this.selectedRowKeys2;
              if(keys.indexOf(record.id) >= 0) {
                flag=true
              }
              if(flag){
                keys.splice(keys.findIndex(item => item === record.id), 1)
                this.selectedRows2.splice(this.selectedRows2.findIndex(item => item === record.id),1)
              } else {
                keys.push(record.id)
                this.selectedRows2.push(record);
              }
            }
          }
        }
      },
      show(customerId){
        this.currentCustomerId = customerId;
        this.onClearSelected();
        this.visible = true;
        this.title = "添加成本制作";
        this.loadData(1,1);
      },
      filterOptionSupplier(input, option){
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      changeSupplier(){
        this.loadData(1,1);
      },
      loadSupplierData(){
        getAction(this.url.supplierList).then((res) => {
          if (res.success) {
            this.supplierData = res.result.records||res.result;
          }else{
            this.$message.warning(res.message)
          }
        })
      },
    }
  }
</script>

<style scoped>
  .ant-card-body .table-operator {
    margin-bottom: 18px;
  }

  .ant-table-tbody .ant-table-row td {
    padding-top: 15px;
    padding-bottom: 15px;
  }

  .anty-row-operator button {
    margin: 0 5px
  }

  .ant-btn-danger {
    background-color: #ffffff
  }

  .ant-modal-cust-warp {
    height: 100%
  }

  .ant-modal-cust-warp .ant-modal-body {
    height: calc(100% - 110px) !important;
    overflow-y: auto
  }

  .ant-modal-cust-warp .ant-modal-content {
    height: 90% !important;
    overflow-y: hidden
  }
</style>